<template>
  <el-date-picker style="max-width: 250px" v-model="value" format="YYYY-MM-DD" :value-format="valueFormat" type="daterange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" :size="size" :shortcuts="shortcuts" @change="change" />
</template>

<script setup lang="ts">
import { watch } from 'vue'
import { addMonths, addWeeks, startOfMonth, startOfToday, subMonths, subWeeks } from 'date-fns'

withDefaults(
  defineProps<{
    size?: 'default' | 'large' | 'small'
    valueFormat?: string
  }>(),
  {
    size: 'small',
    valueFormat: 'YYYY-MM-DD'
  }
)

const value = defineModel('value', { default: '' })
const startTime = defineModel('startTime', { default: '' })
const endTime = defineModel('endTime', { default: '' })
const toDay: Date = startOfToday()
const shortcuts = [
  { text: '今天', value: [toDay, toDay] },
  { text: '本月', value: [startOfMonth(toDay), toDay] },
  { text: '近一周', value: [subWeeks(toDay, 1), toDay] },
  { text: '近一月', value: [subMonths(toDay, 1), toDay] },
  { text: '近三月', value: [subMonths(toDay, 3), toDay] },
  { text: '不限制', value: () => (value.value = '') },
  { text: '未来一周', value: [toDay, addWeeks(toDay, 1)] },
  { text: '未来一月', value: [toDay, addMonths(toDay, 1)] },
  { text: '未来三月', value: [toDay, addMonths(toDay, 3)] }
]

// 监听开始时间，如果开始时间为空，则清空控件值
watch(startTime, (newValue) => {
  if (!newValue) {
    value.value = ''
  }
})

const change = () => {
  if (value.value) {
    startTime.value = value.value[0]
    endTime.value = value.value[1]
  } else {
    startTime.value = ''
    endTime.value = ''
  }
}
</script>

<style lang="scss" scoped></style>
